package model

import (
	"context"
	"gitee.com/DonHz/simple-blog-system/util/hashcode"
	"gitee.com/DonHz/simple-blog-system/util/ormx"
	"gorm.io/gorm"
)

var (
	_all_user_field = ormx.GetGormFields(User{})
)

type GormUserDAO struct {
	db *gorm.DB
}

func NewUserDAO(db *gorm.DB) *GormUserDAO {
	return &GormUserDAO{db: db}
}

func (dao *GormUserDAO) CreateUser(ctx context.Context, name, password string) error {
	password = hashcode.Md5(password)
	user:=User{
		Name:"DonHz",
		Password: password,
	}
	err:= dao.db.Create(&user).Error
	if err!=nil{
		//logger.LogRus.Errorf("create user %s failed: %v", name, err)

	} else {
		//logger.LogRus.Infof("create user id %d", user.Id)
	}
	return err
}

func (dao *GormUserDAO) DeletUse(name string) error {
	err:=dao.db.Where("name=?", name).Delete(User{}).Error
	if err!=nil{
		//logger.LogRus.Errorf("delete user %s failed: %v", name, err)
	}
	return err
}

func (dao *GormUserDAO) GetUserById(ctx context.Context, Id int64) (User, error) {
	var user User
	err:=dao.db.WithContext(ctx).Select(_all_user_field).Where("id=?", Id).First(&user).Error
	if err!=nil{
		if err!=gorm.ErrRecordNotFound {
			//logger.LogRus.Errorf("get user Id %d info failed: %v", Id, err)
		}
		return User{}, err
	}
	return user, nil
}

func (dao *GormUserDAO) GetUserByName(ctx context.Context, name string) (User, error) {
	var user User
	err:=dao.db.WithContext(ctx).Select(_all_user_field).Where("name=?", name).First(&user).Error
	if err!=nil{
		if err!=gorm.ErrRecordNotFound {
			//logger.LogRus.Errorf("get user name %s info failed: %v", name, err)
		}
		return User{}, err
	}
	return user, nil
}

type User struct {
	Id int64 `gorm:"column:id; primaryKey, autoIncrement"`
	Name string `gorm:"column:name; varchar(128), index, unique"`
	Password string	`gorm:"column:password"`
	CreateTime int64 `gorm:"column:create_time"`
	UpdateTime int64 `gorm:"column:update_time"`
}
